package com.example.security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author LiYuhang
 * @version 0.1
 * @application
 */
@Component
public class MyAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    private static final Logger log = LoggerFactory.getLogger(MyAuthenticationFilter.class);


    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,HttpServletResponse response) throws AuthenticationException {

        /**
         * 说明用户以 JSON 的形式传递的参数
         */
        boolean isJsonRequest = request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE);
        log.info("isJsonRequest:{}",isJsonRequest);
        if (isJsonRequest) {
            //获取用户登录信息

            ImmutablePair<String, String> loginRequest = getRequestInfo(request);
            String username = loginRequest.left;
            String password = loginRequest.right;
            log.info("isJsonRequest:{},username:{},password:{}",isJsonRequest,username,password);

            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                    username,password);
            // Allow subclasses to set the "details" property
            setDetails(request,authRequest);

            return this.getAuthenticationManager().authenticate(authRequest);
        }
        return super.attemptAuthentication(request,response);

    }

    private ImmutablePair<String, String> getRequestInfo(HttpServletRequest request) {
        String username = "", password = "";
        try {
            Map<String, String> map = new ObjectMapper().readValue(request.getInputStream(),Map.class);
            username = map.getOrDefault("username","").trim();
            password = map.getOrDefault("password","").trim();
        } catch (IOException e) {
            log.error("捕捉到异常 username:{},password:{},message:{} {}, 异常栈信息:",username,password,e.getMessage(),e);
            e.printStackTrace();
        }
        return ImmutablePair.of(username,password);

    }


}
